package cn.ht.jywrwater.module.ht.service.devicedata;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.ht.jywrwater.module.ht.controller.admin.devicedata.vo.*;
import cn.ht.jywrwater.module.ht.dal.dataobject.devicedata.DeviceDataDO;
import cn.ht.jywrwater.framework.common.pojo.PageResult;

import cn.ht.jywrwater.module.ht.convert.devicedata.DeviceDataConvert;
import cn.ht.jywrwater.module.ht.dal.mysql.devicedata.DeviceDataMapper;

import static cn.ht.jywrwater.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ht.jywrwater.module.ht.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 设备数据 Service 实现类
 *
 * @author hzx
 */
@Service
@Validated
public class DeviceDataServiceImpl implements DeviceDataService {

    @Resource
    private DeviceDataMapper deviceDataMapper;

    @Override
    public Long createDeviceData(DeviceDataCreateReqVO createReqVO) {
        // 插入
        DeviceDataDO deviceData = DeviceDataConvert.INSTANCE.convert(createReqVO);
        deviceDataMapper.insert(deviceData);
        // 返回
        return deviceData.getId();
    }

    @Override
    public void updateDeviceData(DeviceDataUpdateReqVO updateReqVO) {
        // 校验存在
        validateDeviceDataExists(updateReqVO.getId());
        // 更新
        DeviceDataDO updateObj = DeviceDataConvert.INSTANCE.convert(updateReqVO);
        deviceDataMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceData(Long id) {
        // 校验存在
        validateDeviceDataExists(id);
        // 删除
        deviceDataMapper.deleteById(id);
    }

    private void validateDeviceDataExists(Long id) {
        if (deviceDataMapper.selectById(id) == null) {
            throw exception(DEVICE_DATA_NOT_EXISTS);
        }
    }

    @Override
    public DeviceDataDO getDeviceData(Long id) {
        return deviceDataMapper.selectById(id);
    }

    @Override
    public List<DeviceDataDO> getDeviceDataList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return deviceDataMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<DeviceDataDO> getDeviceDataPage(DeviceDataPageReqVO pageReqVO) {
        return deviceDataMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DeviceDataDO> getDeviceDataList(DeviceDataExportReqVO exportReqVO) {
        return deviceDataMapper.selectList(exportReqVO);
    }

    @Override
    public DeviceDataDO getDeviceValue(String deviceCode) {
        List<DeviceDataDO> getByDeviceCodeList = deviceDataMapper.selectList("device_code", deviceCode);
        DeviceDataDO deviceDataLatest = getByDeviceCodeList.stream().max(Comparator.comparing(DeviceDataDO::getDataTime)).get();
        return deviceDataLatest;
    }

}
